<template>
  <div class="container">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="trees">
            <el-tree
              :data="organization.list"
              icon-class="el-icon-plus"
              highlight-current
              :default-expanded-keys="[1]"
              node-key="id"
              
              @node-click="treeNodeContextmenu"
            />
          </div>
        </el-col>
        <el-col :span="8">
          <div class="edit_content">
              <el-form
                ref="addOrganizationForm"
                :rules="addOrganization.rules"
                :model="editOrganization.form"
                label-width="80px"
              >
                <el-form-item prop="name" label="机构名称">
                  <el-input v-model="editOrganization.form.name"></el-input>
                </el-form-item>
                <el-form-item label="机构属性">
                  <el-input disabled v-model="editOrganization.form.level"></el-input>
                </el-form-item>
                <!-- <div class="add_btns">
                  <el-button type="primary" @click="editTeam">保 存</el-button>
                  <el-button type="success" @click="editOrganization.show = false">取 消</el-button>
                </div> -->
              </el-form>
            </div>
          </el-col>
      </el-row>
  </div>
</template>
<script>
import '@/assets/css/common.css'
import { formatDate } from '@/common/js/date.js'
import export2Excel from '@/utils/exportExcel/index.js'
export default {
  data () {
    return {
      organizationShow: false,
      organization: {
        show: false,
        list: []
      },
      // 添加班组
      addOrganization: {
        show: false,
        addRules: {
          name: [
            { required: true, message: '请输入机构名称', trigger: 'blur' }
          ]
        },
        form: {
          name: '',
          attribute: '',
          preName: '',
          ParentNo: 0
        }
      },
      // 编辑班组
      editOrganization: {
        show: false,
        form: {
          name: '',
          clientNo: '',
          PARENT_NO: ''
        }
      },
      addShow: true,
      editShow: true,
      selectBox: true,
      currentPage: 1, //初始页
      pageSize: 10,    //    每页的数据
      // 人员管理
      person: {
        name: '',
        client: '',
        clientList: []
      },
      // 新增人员
      newPersonForm: {
        show: false,
        Name: '',
        Phone: '',
        SimCardNo: '',
        BirhDay: '',
        WorkDate: '',
        Sex: '男',
        WorkType: '',
        ClientNo: ''
      },
      tableData: [],
      originalData: []
    }
  },
  created () {
    // this.getTeamList();
    this.getOrganizationList();
  },
  methods: {
    // 获取组织机构列表
    async getOrganizationList () {
      this.organization.list = []
      const { data } = await this.$Http.get('/DataListCompany/GetClientCleanerListApiNew?ClientNo=' + localStorage.getItem('CLIENT_NO'))

      data.forEach(item => {
        const obj = {}
        obj.id = 1
        obj.label = item.CLIENT_NAME
        obj.children = item.cleaningTeams

        this.organization.list.push(obj)
      })

      this.organization.list = this.organization.list.filter(item => {
        item.children = item.children.filter(ele => {
          ele.label = ele.CLIENT_NAME
          ele.children = ele.teams
          delete ele.CLIENT_NAME
          delete ele.teams

          ele.children = ele.children.filter(e => {
            e.label = e.CLIENT_NAME
            delete e.CLIENT_NAME
            return e
          })
          return ele
        })
        return item
      })
    },
    // 右键树形节点
    treeNodeContextmenu (event, dataObj, node, d) {
      // console.log(dataObj)
      // // 获取整体弹窗位置
      // const organizationLocation = document.querySelector('.organization').getBoundingClientRect()

      // this.selectBox = true
      // // 设置选择框的位置
      // this.$refs.selectBox.style.left = event.clientX - organizationLocation.left + 'px'
      // this.$refs.selectBox.style.top = event.clientY - organizationLocation.top + 'px'

      // if (node.level === 2) {
      //   this.addOrganization.form.attribute = '班组'
      //   this.addOrganization.form.preName = dataObj.label
      //   this.addOrganization.form.ParentNo = dataObj.CLIENT_NO
      //   this.addShow = true
      //   this.editShow = false
      // }
      // if (node.level === 3) {
      //   this.editShow = true
      //   this.addShow = false
        this.editOrganization.form.name = dataObj.data.label
        this.editOrganization.form.clientNo = dataObj.data.CLIENT_NO
        this.editOrganization.form.PARENT_NO = dataObj.data.PARENT_NO
        this.editOrganization.form.level = '清扫队'
        if (dataObj.data.PARENT_NO.length > 7){
          this.editOrganization.form.level = '班组'
        }
    },
    // 添加班组按钮
    addNewOrganization () {
      this.addOrganization.show = true
      this.addOrganization.form.name = ''
      this.editOrganization.show = false
      this.selectBox = false
    },
    // 编辑班组按钮
    editNewOrganization () {
      this.editOrganization.show = true
      this.addOrganization.show = false
      this.selectBox = false
    },
    // 编辑班组
    async editTeam () {
      if (this.editOrganization.form.name === '') {
        this.$message({
          showClose: true,
          message: '机构名称不能为空！！',
          type: 'warning'
        })
        return false
      }
      const params = {
        ClientNo: this.editOrganization.form.clientNo,
        ClientName: this.editOrganization.form.name,
        ParentNo: this.editOrganization.form.PARENT_NO,
        CreateTime: new Date().toLocaleDateString().split('/').join('-') + ' ' + new Date().toTimeString().split(' ')[0]
      }
      await this.$Http.get('/DataListCompany/UpdateTeamApi', { params })
      // 刷新树形结构
      this.getOrganizationList()
      this.editOrganization.show = false
    },
    // 删除班组
    async deleteOrganization () {
      await this.$Http.get(`/DataListCompany/DeleteTeamApi?ClientNo=${this.editOrganizationForm.clientNo}`)
      this.getOrganizationList()
      this.selectBox = false
    },
    // 添加组织机构
    async addTeam () {
      if (this.addOrganization.form.name === '') {
        this.$message({
          showClose: true,
          message: '机构名称不能为空！！',
          type: 'warning'
        })
        return false
      }
      const { data } = await this.$Http.get(`/DataListCompany/GetMaxNoApi?ClientNo=${this.addOrganization.form.ParentNo}`)
      // 新班组编号
      let newClientNo = ''
      const maxClientNo = Number(data[0].ClientNo.substr(9))
      newClientNo = maxClientNo + 1
      if (newClientNo < 10) newClientNo = '0' + newClientNo
      newClientNo = this.addOrganization.form.ParentNo + newClientNo
      // 参数
      const params = {
        ClientNo: newClientNo,
        ClientName: this.addOrganization.form.name,
        ParentNo: this.addOrganization.form.ParentNo,
        CreateTime: new Date().toLocaleDateString().split('/').join('-') + ' ' + new Date().toTimeString().split(' ')[0]
      }
      await this.$Http.get('/DataListCompany/AddTeamApi', { params })
      // 刷新树形结构
      this.getOrganizationList()
      this.addOrganization.show = false
    },
    async getTeamList () {
      const { data } = await this.$Http.get('DataListCompany/GetCleaneranceApi?ClientNo=' + localStorage.getItem('CLIENT_NO'))
      this.person.clientList = data
      this.person.clientList.unshift({ "CLIENT_NO": "0", "CLIENT_NAME": "全部" })
      // this.attendanceMonth.records.teamList = data
    },
    async getlistdata () {
      var url = 'DataListCompany/GetTeamWorkApi?ClientNo=' + localStorage.getItem('CLIENT_NO')
      const { data } = await this.$Http.get(url)
      this.originalData = data

      this.personQuery()
    },
    // 人员管理查询
    personQuery () {
      this.tableData = this.originalData
      const { name, client } = this.person
      if (name) this.tableData = this.tableData.filter(item => item.CLIENT_NAME.includes(name))
      if (client) this.tableData = this.tableData.filter(item => item.CLIENT_NO.includes(client))
    },
    // 新增人员
    addNewPerson () {
      this.editPersonShow = false
      this.person.listShow = false
      this.newPersonForm = {
        show: true,
        Name: '',
        Phone: '',
        SimCardNo: '',
        BirhDay: '',
        WorkDate: '',
        Sex: '男',
        WorkType: '',
        ClientNo: ''
      }
    },
    async addPerson (formName) {
      for (const k in this.newPersonForm) {
        if (this.newPersonForm[k] === '') {
          this.$message({
            message: '表单项不能为空！！',
            type: 'warning'
          })
          return false
        }
      }
      const { data } = await this.$Http.get('/DataListCompany/AddWorkerApi', {
        params: this.newPersonForm
      })
      if (data.IsSucess) {
        this.$message({
          message: '新增成功！！！',
          type: 'success'
        })
        this.getlistdata()
        this.resetForm('newPersonForm')
        this.newPersonForm.show = false
      }
    },
    // 重置新增人员表单
    resetForm (formName) {
      this.$refs[formName].resetFields()
      // this.newPersonForm.SimCardNo = ''
      // this.newPersonForm.BirhDay = ''
      // this.newPersonForm.WorkDate = ''
      this.newPersonForm = {
        show: true,
        Name: '',
        Phone: '',
        SimCardNo: '',
        BirhDay: '',
        WorkDate: '',
        Sex: '男',
        WorkType: '',
        ClientNo: ''
      }
    },
    async handleEdit (index, row) {

      //   this.idx = index;
      //   this.form = row;
      //   this.editVisible = true;
      const { data } = await this.$Http.get('/DataListCompany/DeleteWorkerApi?VID=' + row.VID)
      if (data.IsSucess) {
        this.$message({
          message: '删除成功！！！',
          type: 'success'
        })
        this.getlistdata()
      }
    },
    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage;
      // console.log(this.currentPage)
      // this.$set(this.query, 'pageIndex', val);
      // this.getData();
    },
    handleSizeChange (size) {
      this.pageSize = size;
      console.log(this.pageSize)
    }
  }
}
</script>
<style scoped lang='less'>
.content {
  overflow-y: scroll;
}
.el-col-6 {
  min-width: 400px;
  min-height: 50px;
}
.el-table th {
  height: 40px;
}
.new_person {
  .el-form {
    width: 260px;
    // height: 180px;
    margin: 10px auto;
    background-color: #fff;
    .el-form-item {
      margin-bottom: 20px;
    }
    .btns {
      display: flex;
      align-items: center;
      justify-content: center;
      // padding-top: 10px;
      .el-button {
        margin: 0 10px;
        /deep/span {
          padding: 0 5px;
        }
      }
    }
  }
}
</style>